###################################################
## Demographic Analysis
## SCRIPT 2: Simulations for precinct 
## assignment tests.
## 
## Script to run mergesplit under Census 
## and both DAS versions.
##
## 5/17/21
###################################################

library(ppmf)
library(geomander)
library(tidyverse)
library(sf)
library(redist)

la_all <- readRDS("../../data/LA/la.Rds") %>%
  rename(sld_upper = sld_up,
         sld_lower = sld_low) %>%
  filter(sld_lower != 106)

la_map <- la_all %>%
  st_set_crs(26915) %>% 
  st_transform(crs = 4269) %>%
  redist_map(
    total_pop = pop,
    pop_tol = 0.05,
    existing_plan = sld_lower
  )

la_map4 <- la_all %>%
  st_set_crs(26915) %>%
  st_transform(crs = 4269) %>%
  redist_map(
    total_pop = v4_pop,
    pop_tol = 0.05,
    existing_plan = sld_lower
  )

la_map12 <- la_all %>%
  st_set_crs(26915) %>% 
  st_transform(crs = 4269) %>%
  redist_map(
    total_pop = v12_pop,
    pop_tol = 0.05,
    existing_plan = sld_lower
  )

##################################################################
## districts in EBR to focus on

district_focus <- c(29, 61, 63:71, 101, 18, 62, 60)

ebr_map <- la_map %>% filter(sld_lower %in% district_focus)
ebr_map4 <- la_map4 %>% filter(sld_lower %in% district_focus)
ebr_map12 <- la_map12 %>% filter(sld_lower %in% district_focus)

##################################################################
## simulate plans
## 500k under each census dataset, otherwise identical

plans_smc <- redist_mergesplit(ebr_map,
                               init_plan = match(ebr_map$sld_lower, 
                                                 unique(ebr_map$sld_lower)),
                               nsims = 500000, 
                               warmup = 1) %>%
  add_reference(ebr_map$sld_lower, "2010 Adopted")

filename <- paste("../../data/LA/sim/mmd_test/novra500k2_census_", 0.05, ".rds", sep = "")
saveRDS(plans_smc, file = filename); rm(plans_smc)
 
plans4_smc <- redist_mergesplit(ebr_map4,
                                init_plan = match(ebr_map4$sld_lower, 
                                                  unique(ebr_map4$sld_lower)),
                                nsims = 500000, 
                                warmup = 1) %>%
  add_reference(ebr_map4$sld_lower, "2010 Adopted")

filename <- paste("../../data/LA/sim/mmd_test/novra500k2_d4_", 0.05, ".rds", sep = "")
saveRDS(plans4_smc, file = filename); rm(plans4_smc)

plans12_smc <- redist_mergesplit(ebr_map12,
                                 init_plan = match(ebr_map12$sld_lower, 
                                                   unique(ebr_map12$sld_lower)),
                                 nsims = 500000, 
                                 warmup = 1) %>%
  add_reference(ebr_map12$sld_lower, "2010 Adopted")

filename <- paste("../../data/LA/sim/mmd_test/novra500k2_d12_", 0.05, ".rds", sep = "")
saveRDS(plans12_smc, file = filename); rm(plans12_smc)
